package com.ruoyi.my.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.my.domain.Login;
import com.ruoyi.my.service.ILoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 微信小程序登录控制器
 */
@RestController
@RequestMapping("/wechat")
public class LoginController {
    @Autowired
    private ILoginService loginService;
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    
    // 微信小程序配置（需要在 application.yml 中配置）
    @Value("${wechat.appId:}")
    private String appId;
    
    @Value("${wechat.appSecret:}")
    private String appSecret;
    
    /**
     * 微信小程序登录
     * @param loginData 登录数据
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult wechatLogin(@RequestBody JSONObject loginData) {
        try {
            System.out.println("================== 微信登录请求 ==================");
            System.out.println("接收时间: " + new java.util.Date());
            System.out.println("请求数据: " + loginData);
            
            // 获取前端传来的数据
            String code = loginData.getString("code");
            String encryptedData = loginData.getString("encryptedData");
            String iv = loginData.getString("iv");
            String signature = loginData.getString("signature");
            JSONObject userInfo = loginData.getJSONObject("userInfo");
            
            System.out.println("登录凭证 code: " + code);
            System.out.println("用户昵称: " + (userInfo != null ? userInfo.getString("nickName") : "未获取"));
            
            // 调用微信接口获取 openId 和 session_key
            String openId = getOpenId(code);

            if (openId != null) {
                System.out.println("✅ OpenID: " + openId);
                
                // 检查 OpenID 是否已注册
                boolean isRegistered = false;
                Login existingLogin = null;
                
                if (loginService != null) {
                    existingLogin = loginService.selectLoginByWeixinId(openId);
                    isRegistered = (existingLogin != null);
                }
                
                if (isRegistered) {
                    System.out.println("✅ 用户已注册，学生ID: " + existingLogin.getStudentId());
                } else {
                    System.out.println("⚠️  首次登录，需要注册");
                }
                System.out.println("=============================================");
                
                // 返回成功结果
                AjaxResult result = AjaxResult.success("登录成功");
                result.put("openId", openId);
                result.put("userInfo", userInfo);
                result.put("isRegistered", isRegistered);  // 是否已注册
                result.put("isFirstLogin", !isRegistered);  // 是否首次登录
                if (isRegistered && existingLogin != null) {
                    result.put("studentId", existingLogin.getStudentId());
                }
                return result;
            } else {
                System.out.println("❌ 获取 OpenID 失败");
                System.out.println("=============================================");
                return AjaxResult.error("获取用户信息失败");
            }
            
        } catch (Exception e) {
            System.err.println("【错误】微信登录失败: " + e.getMessage());
            logger.error("微信登录失败", e);
            e.printStackTrace();
            return AjaxResult.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 调用微信接口获取 openId
     * @param code 临时登录凭证
     * @return openId
     */
    private String getOpenId(String code) {
        try {
            // 检查配置
            if (appId == null || appId.isEmpty() || appSecret == null || appSecret.isEmpty()) {
                System.out.println("⚠️  警告: 未配置微信小程序 appId 和 appSecret");
                System.out.println("请在 application.yml 中配置:");
                System.out.println("wechat:");
                System.out.println("  appId: 你的appId");
                System.out.println("  appSecret: 你的appSecret");
                return "mock_openid_for_test"; // 返回测试用的 openId
            }
            
            // 微信接口地址
            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code
            );
            
            System.out.println("调用微信接口: " + url.replace(appSecret, "******"));
            
            // 发起请求
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.getForObject(url, String.class);
            
            System.out.println("微信接口响应: " + response);
            
            // 解析响应
            JSONObject jsonObject = JSONObject.parseObject(response);
            
            if (jsonObject.containsKey("openid")) {
                String openId = jsonObject.getString("openid");
                String sessionKey = jsonObject.getString("session_key");
                String unionId = jsonObject.getString("unionid");
                
                System.out.println("Session Key: " + sessionKey);
                if (unionId != null) {
                    System.out.println("Union ID: " + unionId);
                }
                
                return openId;
            } else {
                Integer errcode = jsonObject.getInteger("errcode");
                String errmsg = jsonObject.getString("errmsg");
                System.err.println("微信接口错误: " + errcode + " - " + errmsg);
                return null;
            }
            
        } catch (Exception e) {
            System.err.println("调用微信接口异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
